<template>
    <div class="crm-contract-container">
        <el-card shadow="hover" class="mb10" v-auth="'crm:contract:list'">
            <el-form :inline="true" :model="search">
                <el-form-item>
                    <el-input v-model="search.contractCode" placeholder="请输入合同编号" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.contractName" placeholder="请输入合同名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item>
                    <Dictionary v-model="search.contractType" dict-label="crm_contract_type" clearable placeholder="请选择合同类型"></Dictionary>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="search.customerName" placeholder="请输入客户/企业名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-input v-model="search.userName" placeholder="请输入所属用户名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-input v-model="search.deptName" placeholder="请输入所属部门名称" prefix-icon="el-icon-search"></el-input>
                </el-form-item>
                <el-form-item v-if="search.more">
					<el-cascader
						placeholder="请选择所属部门"
						v-model="search.deptId"
						:options="depts"
						:props="{expandTrigger: 'hover', emitPath: false, checkStrictly: true, value: 'id', label: 'deptName', children: 'children' }"
						class="w100"
						filterable
						clearable>
					</el-cascader>
				</el-form-item>
                <el-form-item v-if="search.more">
                    <el-input-number v-model="search.awaitReceivable" placeholder="待回款金额" clearable class="w100"></el-input-number>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.awaitReceivableStatus" placeholder="请选择待回款状态" clearable class="w100">
                        <el-option label="未回款" value="1"></el-option>
                        <el-option label="全部回款" value="0"></el-option>
                        <el-option label="有业务增项" value="-1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.expiryStatus" placeholder="请选择到期状态" multiple clearable class="w100">
                        <el-option label="未到期" value="0"></el-option>
                        <el-option label="即将到期" value="1"></el-option>
                        <el-option label="已到期" value="2"></el-option>
                        <el-option label="已续期" value="3"></el-option>
                        <el-option label="已结束" value="4"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.examineStatus" placeholder="请选择审核状态" multiple clearable class="w100">
                        <el-option label="草稿" value="0"></el-option>
                        <el-option label="审核中" value="1"></el-option>
                        <el-option label="通过" value="2"></el-option>
                        <el-option label="驳回" value="3"></el-option>
                        <el-option label="撤回" value="4"></el-option>
                        <el-option label="作废" value="5"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.deliveryStatus" placeholder="请选择交付状态" multiple clearable class="w100">
                        <el-option label="未交付" value="0"></el-option>
                        <el-option label="已交付" value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-select v-model="search.timefield" placeholder="请选择时间" class="w100">
                        <el-option label="创建时间" value="createTime"></el-option>
                        <el-option label="交付时间" value="deliveryTime"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-date-picker type="daterange" align="right" v-model="dateData.value" :shortcuts="dateData.shortcuts" 
                        unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
                </el-form-item>
                <el-form-item v-if="search.more" label="到期天数范围">
                    <el-input-number v-model="search.expiryMinDay" placeholder="Min天数"></el-input-number>
                </el-form-item>
                <el-form-item v-if="search.more">
                    <el-input-number v-model="search.expiryMaxDay" placeholder="Max天数"></el-input-number>
                </el-form-item>
                <el-form-item>
                    <el-button icon="el-icon-search" type="primary" @click="onTableSearch()">查询</el-button>
                    <el-button icon="el-icon-share" type="primary" @click="loadAmountCrmContract">合计</el-button>
                    <el-button icon="el-icon-refresh" @click="onResetSearch()">重置</el-button>
                    <el-button v-if="!search.more" @click="onMoreSearch(true)" type="primary" link>更多</el-button>
                    <el-button v-if="search.more" @click="onMoreSearch(false)" type="info" link>收起</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card shadow="hover">
            <el-button v-auth="'crm:contract:add'" type="primary" class="ml10" icon="el-icon-document-add" @click="onOpenAddCrmContract()">新增</el-button>
            <!-- <el-button v-auth="'crm:contract:edit'" type="primary" class="ml10" icon="el-icon-edit" @click="onOpenEditCrmContract()" :disabled="tableData.selections.length != 1">修改</el-button> -->
            <!-- <el-button v-auth="'crm:contract:remove'" type="primary" class="ml10" icon="el-icon-delete" @click="onTabelRowsDel()" :disabled="tableData.selections.length <= 0">删除</el-button> -->
            <el-table ref="tableCrmContractRef" :data="tableData.data" @selection-change="onTableSelectionChange" style="width: 100%" row-key="id" :row-class-name="tableRowClassName">
                <el-table-column type="selection" align="cneter" width="50" show-overflow-tooltip></el-table-column>
                <el-table-column type="index" align="center" width="50" show-overflow-tooltip>
                    <template #header>
                        <!-- 使用 el-popover 包裹 el-checkbox-group -->
                        <el-popover placement="bottom-start" :width="100" trigger="click">
                            <template #reference>
                                <!-- 点击触发器：这里放置图标 -->
                                <svg-icon name="el-icon-setting" style="cursor: pointer;"></svg-icon>
                            </template>
                            <!-- el-checkbox-group 放置在此处 -->
                            <el-checkbox-group v-model="tableData.header.selections">
                                <el-checkbox v-for="item in tableData.header.data" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
                            </el-checkbox-group>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column label="合同编号" prop="contractCode" v-if="tableData.header.selections.includes('contractCode')" width="150" show-overflow-tooltip></el-table-column>
                <el-table-column label="合同名称" prop="contractName" v-if="tableData.header.selections.includes('contractName')" width="300" show-overflow-tooltip>
                    <template #default="scope">
                        <el-link v-if="scope.row.parentId" :underline="false" @click="onOpenParentCrmContract(scope.row)">
                            <el-tag size="mini">续</el-tag>
                        </el-link>
                        <span v-if="scope.row.parentId">{{scope.row.contractName}}</span>
                        <span v-else>{{scope.row.contractName}}</span>
                    </template>
                </el-table-column>
                <el-table-column label="客户/企业" prop="customerName" v-if="tableData.header.selections.includes('customerName')" width="250" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.customerName && scope.row.enterpriseName">{{scope.row.enterpriseName}}</span>
                        <span v-if="scope.row.customerName == undefined">{{ scope.row.enterpriseName }}</span>
                    </template>
                </el-table-column>
                <!-- <el-table-column label="企业名称" prop="enterpriseName" width="300" show-overflow-tooltip></el-table-column> -->
                <el-table-column label="合同类型" prop="contractType" v-if="tableData.header.selections.includes('contractType')" width="150" show-overflow-tooltip :formatter="loadContractType"></el-table-column>
                <el-table-column label="合同金额" prop="contractAmount" v-if="tableData.header.selections.includes('contractAmount')" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{scope.row.contractAmount}}元</span>
                    </template>
                </el-table-column>
                <el-table-column label="总回款金额" prop="totalReceivable" v-if="tableData.header.selections.includes('totalReceivable')" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{scope.row.totalReceivable}}元</span>
                    </template>
                </el-table-column>
                <el-table-column label="待回款金额" prop="awaitReceivable" v-if="tableData.header.selections.includes('awaitReceivable')" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{scope.row.awaitReceivable}}元</span>
                    </template>
                </el-table-column>
                <el-table-column label="总支出金额" prop="totalExpense" v-if="tableData.header.selections.includes('totalExpense')" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{scope.row.totalExpense}}元</span>
                    </template>
                </el-table-column>
                <el-table-column label="总利润金额" prop="totalProfit" v-if="tableData.header.selections.includes('totalProfit')" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{scope.row.totalProfit}}元</span>
                    </template>
                </el-table-column>
                <el-table-column label="净利润金额" prop="grossProfit" v-if="tableData.header.selections.includes('grossProfit')" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span>{{scope.row.grossProfit}}元</span>
                    </template>
                </el-table-column>
                <el-table-column label="到期状态" prop="expiryStatus" v-if="tableData.header.selections.includes('expiryStatus')" width="100" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.expiryStatus == '0'" class="color-primary">未到期</span>
                        <span v-else-if="scope.row.expiryStatus == '1'" class="color-warning">即将到期</span>
                        <span v-else-if="scope.row.expiryStatus == '2'" class="color-danger">已到期</span>
                        <span v-else-if="scope.row.expiryStatus == '3'" class="color-success">已续期</span>
                        <span v-else-if="scope.row.expiryStatus == '4'" class="color-info">已结束</span>
                    </template>
                </el-table-column>
                <el-table-column label="到期天数" prop="expiryDay" v-if="tableData.header.selections.includes('expiryDay')" width="150" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.expiryDay == -99999"></span>
                        <span v-else-if="scope.row.expiryDay >= 0">还有 {{ scope.row.expiryDay }} 天到期</span>
                        <span v-else-if="scope.row.expiryDay < 0" class="color-danger">已到期 {{ -scope.row.expiryDay }} 天，请及时续期</span>
                    </template>
                </el-table-column>
                <el-table-column label="审核状态" prop="examineStatus" v-if="tableData.header.selections.includes('examineStatus')" width="80" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.examineStatus == '0'" class="color-primary">草稿</span>
                        <span v-else-if="scope.row.examineStatus == '1'" class="color-warning">审核中</span>
                        <span v-else-if="scope.row.examineStatus == '2'" class="color-success">通过</span>
                        <span v-else-if="scope.row.examineStatus == '3'" class="color-danger">驳回</span>
                        <span v-else-if="scope.row.examineStatus == '4'" class="color-primary">撤回</span>
                        <span v-else-if="scope.row.examineStatus == '5'" class="color-info">作废</span>
                    </template>
                </el-table-column>
                <el-table-column label="交付状态" prop="deliveryStatus" v-if="tableData.header.selections.includes('deliveryStatus')" width="80" show-overflow-tooltip>
                    <template #default="scope">
                        <span v-if="scope.row.deliveryStatus == '0'" class="color-info">未交付</span>
                        <span v-else-if="scope.row.deliveryStatus == '1'" class="color-success">已交付</span>
                    </template>
                </el-table-column>
                <el-table-column label="交付时间" prop="deliveryTime" v-if="tableData.header.selections.includes('deliveryTime')" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="所属用户" prop="userName" v-if="tableData.header.selections.includes('userName')" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column label="所属部门" prop="deptName" v-if="tableData.header.selections.includes('deptName')" width="200" show-overflow-tooltip></el-table-column>
                <el-table-column label="创建时间" prop="createTime" v-if="tableData.header.selections.includes('createTime')" width="180" show-overflow-tooltip></el-table-column>
                <el-table-column label="操作" fixed="right" show-overflow-tooltip width="130" v-auths="['crm:contract:info', 'crm:contract:edit', 'crm:contract:remove', 'crm:contract:commited', 'crm:contract:approved', 'crm:contract:rejected', 'crm:contract:canceled', 'crm:contract:discard', 'crm:contract:finished', 'crm:contract:renewal', 'crm:contract:delivery', 'crm:contract:undelivery', 'crm:contract:change']">
                    <template #default="scope">
                        <el-button v-auth="'crm:contract:info'" type="primary" link @click="onOpenInfoCrmContract(scope.row)">详情</el-button>
                        <el-dropdown class="ml10" style="vertical-align:unset" v-auths="['crm:contract:edit', 'crm:contract:remove', 'crm:contract:commited', 'crm:contract:approved', 'crm:contract:rejected', 'crm:contract:canceled', 'crm:contract:discard', 'crm:contract:finished', 'crm:contract:renewal', 'crm:contract:delivery', 'crm:contract:undelivery', 'crm:contract:change']">
                            <span class="el-dropdown-link">
                                <el-button type="primary" link>更多 <i class="fa fa-angle-down"></i></el-button>
                            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <div v-auth="'crm:contract:edit'" v-show="['0','2','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenEditCrmContract(scope.row, 'edit')">修改</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:contract:remove'" v-show="['0','3','4','5'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onTabelRowDel(scope.row)">删除</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:contract:commited'" v-show="['0','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '1')">提交</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:contract:approved'" v-show="['1'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '2')">通过</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:contract:rejected'" v-show="['1','2'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '3')">驳回</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:contract:canceled'" v-show="['1'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '4')">撤回</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:contract:discard'" v-show="['0','3','4'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenExamineRecordStatus(scope.row, '5')">作废</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:contract:finished'" v-show="!['4'].includes(scope.row.expiryStatus) && ['2'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenFinishedCrmContract(scope.row)">终止</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:contract:renewal'" v-show="!['3'].includes(scope.row.expiryStatus) && ['2'].includes(scope.row.examineStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenEditCrmContract(scope.row, 'renewal')">续期</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:contract:delivery'" v-show="['0'].includes(scope.row.deliveryStatus) && scope.row.awaitReceivable <= 0">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenDeliveryCrmContract(scope.row)">交付</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:contract:undelivery'" v-show="['1'].includes(scope.row.deliveryStatus)">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenUnDeliveryCrmContract(scope.row)">取消交付</el-button>
                                        </el-dropdown-item>
                                    </div>
                                    <div v-auth="'crm:contract:change'">
                                        <el-dropdown-item>
                                            <el-button type="primary" link @click="onOpenChangeCrmContract(scope.row)">变更</el-button>
                                        </el-dropdown-item>
                                    </div>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="onPageSizeChange"
                @current-change="onPageCurrentChange"
                class="mt15"
                :pager-count="5"
                :page-sizes="[10, 20, 30, 40, 50, 60]"
                v-model:current-page="search.pageNum"
                v-model:page-size="search.pageSize"
                layout="total, sizes, prev, pager, next, jumper, slot"
                :total="tableData.total"
            >
                <template #default v-if="contractAmountShow">
                    <el-text class="ml10 color-warning">总合同金额：{{ contractAmount.contractAmount }} 元</el-text>
                    <el-text class="ml10 color-warning">总回款金额：{{ contractAmount.totalReceivable }} 元</el-text>
                    <el-text class="ml10 color-warning">待回款金额：{{ contractAmount.awaitReceivable }} 元</el-text>
                    <el-text class="ml10 color-warning">总支出金额：{{ contractAmount.totalExpense }} 元</el-text>
                    <el-text class="ml10 color-warning">总利润金额：{{ contractAmount.totalProfit }} 元</el-text>
                    <el-text class="ml10 color-warning">净利润金额：{{ contractAmount.grossProfit }} 元</el-text>
                    <slot></slot>
                </template>
            </el-pagination>
        </el-card>
        <AddCrmContract ref="addCrmContractRef" @submit="onTableSearch"/>
        <EditCrmContract ref="editCrmContractRef" @submit="onTableSearch"/>
        <ChangeCrmContract ref="changeCrmContractRef" @submit="onTableSearch"/>
        <InfoCrmContract ref="infoCrmContractRef"></InfoCrmContract>
    </div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, watch, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Local } from '/@/utils/storage';
import AddCrmContract from '/@/views/crm/contract/addCrmContract.vue';
import EditCrmContract from '/@/views/crm/contract/editCrmContract.vue';
import InfoCrmContract from '/@/views/crm/contract/infoCrmContract.vue';
import ChangeCrmContract from '/@/views/crm/contract/changeCrmContract.vue';
import { getCrmContractList, delCrmContract, finishedCrmContract, examineCrmContract, deliveryCrmContract, undeliveryCrmContract, amountCrmContract } from '/@/api/crm/contract/index';
import { getDictionaryByLabel } from '/@/api/system/dictionary/index';
import { formatDate, getDateRangeShortcuts } from '/@/utils/formatTime';
import Dictionary from '/@/components/dictionary/index.vue';
import { getCrmDeptList } from '/@/api/crm/dept/index';
import { lineToTreeData } from '/@/utils/commonFunction';
export default {
    name: 'crm/contract',
    components: { AddCrmContract, EditCrmContract, ChangeCrmContract, InfoCrmContract, Dictionary },
    setup() {
        const tableCrmContractRef = ref();
        const addCrmContractRef = ref();
        const editCrmContractRef = ref();
        const changeCrmContractRef = ref();
        const infoCrmContractRef = ref();
        const state = reactive({
            contractTypes: [],
            contractAmountShow: false,
            contractAmount: {
                contractAmount: 0,
                totalReceivable: 0,
                awaitReceivable: 0,
                totalExpense: 0,
                totalProfit: 0,
                grossProfit: 0,
            },
            depts: [],
            search:{
                contractCode: undefined,
                contractName: undefined,
                contractType: undefined,
                customerName: undefined,
                awaitReceivable: undefined,
                awaitReceivableStatus: undefined,
                examineStatus: [],
                expiryStatus: [],
                deliveryStatus: [],
                expiryMinDay: undefined,
                expiryMaxDay: undefined,
                userName: undefined,
                deptName: undefined,
                deptId: undefined,
                timefield: 'createTime',
                startTime: '',
                endTime: '',
                orderBy: 'createTime',
				isAsc: 'desc',
                pageNum: 1,
                pageSize: 10,
                more: false,
            },
            dateData: {
                value: [],
                shortcuts: getDateRangeShortcuts()
            },
            tableData: {
                selections: [],//选中的行数据
                data: [],
                total: 0,
                loading: false,
                header: {
                    selections: ['contractCode', 'contractName', 'customerName', 'contractType', 'contractAmount', 'totalReceivable', 'awaitReceivable', 'totalExpense', 'totalProfit', 'grossProfit', 'expiryStatus', 'expiryDay', 'examineStatus', 'deliveryStatus', 'deliveryTime', 'userName', 'deptName', 'createTime'],
                    data: [
                        {label: '合同编号', value: 'contractCode'},
                        {label: '合同名称', value: 'contractName'},
                        {label: '客户/企业', value: 'customerName'},
                        {label: '合同类型', value: 'contractType'},
                        {label: '合同金额', value: 'contractAmount'},
                        {label: '总回款金额', value: 'totalReceivable'},
                        {label: '待回款金额', value: 'awaitReceivable'},
                        {label: '总支出金额', value: 'totalExpense'},
                        {label: '总利润金额', value: 'totalProfit'},
                        {label: '净利润金额', value: 'grossProfit'},
                        {label: '到期状态', value: 'expiryStatus'},
                        {label: '到期天数', value: 'expiryDay'},
                        {label: '审核状态', value: 'examineStatus'},
                        {label: '交付状态', value: 'deliveryStatus'},
                        {label: '交付时间', value: 'deliveryTime'},
                        {label: '所属用户', value: 'userName'},
                        {label: '所属部门', value: 'deptName'},
                        {label: '创建时间', value: 'createTime'},
                    ],
                }
            }
        });

        const loadTableData = (params) => {
            state.contractAmountShow = false;
            const search = { ...state.search, ...params };
            const examineStatusStr = search.examineStatus.join(',');
            const expiryStatusStr = search.expiryStatus.join(',');
            const deliveryStatusStr = search.deliveryStatus.join(',');
            getCrmContractList({
                ...search,
                examineStatus: examineStatusStr,
                expiryStatus: expiryStatusStr,
                deliveryStatus: deliveryStatusStr
            }).then((res) => {
                if(res.code == 0){
                    state.tableData.data = res.data;
                    state.tableData.total = res.total;
                    tableCrmContractRef.value.clearSelection();
                }
            });
        }

        //查询
        const onTableSearch = () => {
            if(state.dateData.value.length == 2){
                state.search.startTime = formatDate(state.dateData.value[0], 'yyyy-MM-dd') + ' 00:00:00';
                state.search.endTime = formatDate(state.dateData.value[1], 'yyyy-MM-dd') + ' 23:59:59';
            }
            loadTableData(state.search);
        }
        //重置
        const onResetSearch = () => {
            state.dateData.value = [];
            state.search.contractCode = undefined;
            state.search.contractName = undefined;
            state.search.contractType = undefined;
            state.search.customerName = undefined;
            state.search.awaitReceivable = undefined;
            state.search.awaitReceivableStatus = undefined;
            state.search.examineStatus = [];
            state.search.expiryStatus = [];
            state.search.deliveryStatus = [];
            state.search.expiryMinDay = undefined;
            state.search.expiryMaxDay = undefined;
            state.search.userName = undefined;
            state.search.deptName = undefined;
            state.search.deptId = undefined;
            state.search.startTime = undefined;
            state.search.endTime = undefined;
            state.search.pageNum = 1;
            state.search.pageSize = 10;
            loadTableData(state.search);
        }
        const onMoreSearch = (more: boolean) => {
            state.search.more = more;
        };
        // 监听表格选中行
        const onTableSelectionChange = (selections) =>{
            state.tableData.selections = selections;
        };
        // 每页显示数据大小改变
        const onPageSizeChange = (val: number) => {
            state.search.pageSize = val;
            loadTableData(state.search);
        };
        // 页码改变
        const onPageCurrentChange = (val: number) => {
            state.search.pageNum = val;
            loadTableData(state.search);
        };
        // 打开新增弹窗
        const onOpenAddCrmContract = (row?: object) => {
            addCrmContractRef.value.openDialog(row);
        };
        // 打开编辑弹窗
        const onOpenEditCrmContract = (row: object, operate: string) => {
            row = row || state.tableData.selections[0];
            row.operate = operate;
            editCrmContractRef.value.openDialog(row);
        };
        // 打开变更弹窗
        const onOpenChangeCrmContract = (row: object) => {
            row = row || state.tableData.selections[0];
            changeCrmContractRef.value.openDialog(row);
        };

        const tableRowClassName = (row, index) => {
            if(row.expiryStatus == '1'){
                return 'color-warning';
            }else if(row.examineStatus == '2'){
                return 'color-danger';
            }else{
                return '';
            }
        };

        // 删除选中行
        const onTabelRowsDel = () => {
            const ids = state.tableData.selections.map(item => item.id);
            if(ids && ids.length > 0){
                ElMessageBox.confirm('确定删除选中的合同信息吗？', '提示', {
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    delCrmContract(ids).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('删除成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }
        };
        // 删除当前行
        const onTabelRowDel = (row: object) => {
            ElMessageBox.confirm('确定删除该条合同信息吗？', '提示', {
                confirmButtonText: '删除',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                delCrmContract([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('删除成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };

        const loadContractType = (row, column, cellValue, index) => {
            return state.contractTypes.find((item) => item.dictValue == cellValue)?.dictName;
        }

        const onOpenInfoCrmContract = (row: object) => {
            infoCrmContractRef.value.openDialog(row);
        }

        const onOpenParentCrmContract = (row: object) => {
            infoCrmContractRef.value.openDialog({id: row.parentId});
        }

        const examineStatusText = (status: String) => {
            const statusMap = {
                '0': '草稿',
                '1': '提交',
                '2': '通过',
                '3': '驳回',
                '4': '撤回',
                '5': '作废'
            };
            return statusMap[status] || '未知';
        };
        
        const onOpenExamineRecordStatus = (row: object, status: String) => {
            if(['1', '4', '5'].includes(status)){
                ElMessageBox.confirm(`确认【${ examineStatusText(status) }】操作吗？`, '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    examineCrmContract({ examineTargetId: row.id, status: status }).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('操作成功');
                            loadTableData({});
                        }
                    });
                }).catch(() => {});
            }else if(status == '3'){
                ElMessageBox.prompt('请输入驳回原因：', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then((message) => {
                    if (!message.value || message.value.trim() === '') {
                        ElMessage.error('驳回原因不能为空，请重新输入！');
                    } else {
                        examineCrmContract({ examineTargetId: row.id, status: status, examineReason: message.value }).then((res) => {
                            if(res.code === 0){
                                ElMessage.success('操作成功');
                                loadTableData({});
                            }
                        });
                    }
                }).catch(() => {});
            }else if(status == '2'){
                ElMessageBox.prompt('请输入通过原因：', '提示', {
                    confirmButtonText: '确认',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then((message) => {
                    if (!message.value || message.value.trim() === '') {
                        ElMessage.error('通过原因不能为空，请重新输入！');
                    } else {
                        examineCrmContract({ examineTargetId: row.id, status: status, examineReason: message.value }).then((res) => {
                            if(res.code === 0){
                                ElMessage.success('操作成功');
                                loadTableData({});
                            }
                        });
                    }
                }).catch(() => {});
            }
        };

        const onOpenFinishedCrmContract = (row: object) => {
            ElMessageBox.confirm(`确认【终止】合同操作吗？`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                finishedCrmContract([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('操作成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };
        const onOpenDeliveryCrmContract = (row: object) => {
            ElMessageBox.confirm(`确认【交付】合同操作吗？`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                deliveryCrmContract([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('操作成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };

        const onOpenUnDeliveryCrmContract = (row: object) => {
            ElMessageBox.confirm(`确认【取消交付】合同操作吗？`, '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                undeliveryCrmContract([row.id]).then((res) => {
                    if(res.code === 0){
                        ElMessage.success('操作成功');
                        loadTableData({});
                    }
                });
            }).catch(() => {});
        };

        const loadAmountCrmContract = (params: object) => {
            state.contractAmountShow = true;
            const search = { ...state.search, ...params };
            const examineStatusStr = search.examineStatus.join(',');
            const expiryStatusStr = search.expiryStatus.join(',');
            const deliveryStatusStr = search.deliveryStatus.join(',');
            amountCrmContract({
                ...search,
                examineStatus: examineStatusStr,
                expiryStatus: expiryStatusStr,
                deliveryStatus: deliveryStatusStr
            }).then((res) => {
                if(res.code === 0){
                    state.contractAmount = res.data;
                }
            });
        };

        // 页面加载时
        onMounted(() => {
            const selections = Local.get('crm_contract_header_selections');
            if(selections){
                state.tableData.header.selections = selections;
            }
            loadTableData({});
            getDictionaryByLabel({ dictLabel: 'crm_contract_type' }).then((res: any) => {
                if (res.code == 0) {
                    state.contractTypes = res.data;
                }
            });
            getCrmDeptList().then((res: any) => {
                if(res.code == 0 && res.data?.length > 0){
                    state.depts = lineToTreeData(res.data);
                }
            });
        });

        watch(() => state.tableData.header.selections, (selections) => {
            nextTick(() => {
                Local.set('crm_contract_header_selections', selections)
                tableCrmContractRef.value.doLayout();
            });
        }, { deep: true });

        return {
            tableCrmContractRef,
            addCrmContractRef,
            editCrmContractRef,
            changeCrmContractRef,
            infoCrmContractRef,
            tableRowClassName,
            onTableSearch,
            onResetSearch,
            onMoreSearch,
            onTableSelectionChange,
            onPageSizeChange,
            onPageCurrentChange,
            onOpenAddCrmContract,
            onOpenEditCrmContract,
            onTabelRowsDel,
            onTabelRowDel,
            loadContractType,
            onOpenInfoCrmContract,
            onOpenParentCrmContract,
            onOpenExamineRecordStatus,
            onOpenFinishedCrmContract,
            onOpenChangeCrmContract,
            onOpenDeliveryCrmContract,
            onOpenUnDeliveryCrmContract,
            loadAmountCrmContract,
            ...toRefs(state),
        };
    },
};
</script>